package models;

import play.*;
import play.data.validation.*;
import play.db.jpa.*;
import play.libs.Codec;

import javax.persistence.*;

import java.io.File;
import java.util.*;

@Entity
public class Event extends Model implements Comparable<Event>{
	
	@Required
	public String name;

	@Lob
	public String description;
	
	@Required
	public Date startDate;
	public Date endDate;
	public String street;
	public int streetNumber;
	@Required
	public String city;
	public int zipcode;
	public String eventlink;
	public Blob picture;
	public int clicks;
	public boolean isActive;
	@Required
	public EventCategory category;
	
	@OneToMany(mappedBy = "event", cascade = CascadeType.ALL)
	public List<Offer> offers;
	
	/**
	 * 
	 * @param name The event's name
	 * @param startDate The event's startDate
	 * @param city The event's city
	 * @param category The event's category
	 */
	public Event(String name, Date startDate, String city, EventCategory category){
		this.name = name;
		this.startDate = startDate;
		this.city = city;
		this.category = category;
		this.isActive = false;
	}
	/**
	 * Find the Event with the given name and start date
	 * @param eventName Name of the event
	 * @param startDate Start date of the event
	 * @return the Event found
	 */
	public static Event findByNameAndDate(String eventName, Date startDate){
		return find("Select e from Event e where e.name = ? and e.startDate = ?", eventName, startDate).first();
	}
	
	/**
	 * 
	 * @param eventName The name of the event
	 * @param startDate The start date of the event
	 * @return true if event exists already, otherwise false
	 */
	public static boolean isEventExistent(String eventName, Date startDate){
		return findByNameAndDate(eventName, startDate) != null;
	}
	
	public Event addOffer(Offer o){
		offers.add(o);
		return this;
	}
	
	public Event removeOffer(Offer o){
		offers.remove(o);
		return this;
	}
	
	@Override
	public int compareTo(Event o) {
		if (o.startDate.getTime()<this.startDate.getTime())
			return 1;
		else if (o.startDate.getTime()>this.startDate.getTime())
			return -1;
		return 0;
	}
}
